package com.yang.controller;

import com.yang.entity.Address;
import com.yang.entity.PageBean;
import com.yang.entity.Result;
import com.yang.service.AddressService;
import com.yang.service.UserService;
import com.yang.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private AddressService addressService;

    /**
     * 新增用户收货地址
     *
     * @param address 收货地址实体类
     * @return
     */
    @PostMapping("/addAddress")
    public Result addAddress(@RequestBody @Validated Address address) {
        System.out.println("user/addAddress =====>");
        // 获取用户信息
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        // 用户地址只能为5条
        if (addressService.userAddressCount(userId) >= 5) {
            return Result.error("用户地址只能为5条");
        }
        // 新增地址信息
        address.setUserId(userId);
        addressService.addAddress(address);
        return Result.success();

    }

    /**
     * 获取用户相关的地址信息
     *
     * @author 杨鑫
     */
    @GetMapping("/addressList")
    public Result<List<Address>> addressList() {
        System.out.println("user/addressList =====>");
        // 查询用户地址信息
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        List<Address> addressList = addressService.findAddressByUserId(userId);
        return Result.success(addressList);
    }

    /**
     * 删除用户收货地址
     *
     * @param addressId 收货地址id
     * @return
     */
    @PostMapping("/deleteAddress")
    public Result deleteAddress(Integer addressId) {
        System.out.println("user/deleteAddress =====>");
        // 获取用户信息
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        // 删除用户收货地址
        addressService.deleteAddress(userId, addressId);
        return Result.success();
    }

    /**
     * 修改用户收货地址
     *
     * @param address
     * @return
     */
    @PostMapping("/updateAddress")
    public Result updateAddress(@RequestBody @Validated Address address) {
        System.out.println("user/updateAddress =====>");
        // 获取用户信息
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        address.setUserId(userId);
        // 修改用户收货地址
        addressService.updateAddress(address);
        return Result.success();
    }
}
